<template>
  <div class="wrap">
    <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-width="120px" class="demo-ruleForm">
      <el-form-item label="username" prop="username">
        <el-input v-model="ruleForm.username" type="text" autocomplete="off" />
      </el-form-item>
      <el-form-item label="password" prop="password">
        <el-input v-model="ruleForm.password" type="password" autocomplete="off"
          @keyup.enter.native="submitForm(ruleFormRef)" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">Submit</el-button>
        <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { Login } from '../apis/user'
import { useRouter } from 'vue-router'
import initMenu from '../stores/counter'
const MenuObj = initMenu()
const router = useRouter()

const ruleFormRef = ref<FormInstance>()

const checkAge = (rule, value: number, callback: Function) => {
  if (!value) {
    return callback(new Error('Please input the age'))
  }
  setTimeout(() => {
    if (!Number.isInteger(value)) {
      callback(new Error('Please input digits'))
    } else {
      if (value < 18) {
        callback(new Error('Age must be greater than 18'))
      } else {
        callback()
      }
    }
  }, 1000)
}


const ruleForm = reactive({
  username: 'admin',
  password: '1234567',
})

const rules = reactive<FormRules<typeof ruleForm>>({
  password: [{ min: 1, max: 100, required: true, trigger: 'blur', message: "密码必填" }],
  username: [{ min: 1, max: 20, required: true, trigger: 'blur', message: "用户名必填" }],
})

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid) => {
    if (valid) {
      let res = await Login(ruleForm)
      if (res.status == 200) {
        ElMessage({
          message: '登录成功',
          type: 'success',
        })
        sessionStorage.setItem("token", res.data.token)
        sessionStorage.setItem("refreshToken", res.data.refreshToken)
        sessionStorage.setItem("menu", JSON.stringify(res.data.authArr))
        sessionStorage.setItem("username", ruleForm.username)
        router.push('/index')
        MenuObj.getMenu()
      } else {
        ElMessage({
          message: res.data.message,
          type: 'error',
        })
      }
    } else {
      console.log('error submit!')
      return false
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>
<style lang="less" scoped>
.wrap {
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: space-around;
  align-items: center;
  background: url('http://m.liyefeng.top/static/upload/banner/1710832132bj.webp');
  background-size: 100% 100%;
}
</style>
